import 'dart:math' as fixMath;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../lib_baseview/lib_baseview.dart';
import '../../lib_baseview/root_page.dart';
import '../../lib_baseview/theme/jr.dart';
import '../../lib_baseview/utils/cache_util.dart';
import '../../lib_baseview/utils/constant/text_styles.dart';
import '../../lib_runtime/global_config.dart';
import '../../lib_user/user_manager.dart';
import '../../resource/language/generated/l10n.dart';
import '../main/main_page.dart';
import 'mine_page_controller.dart';

enum MinePageItem {
  wallet,
  car,
  dress,
  level,
  knight,
}

///我的
class MinePage extends StatefulWidget {
  const MinePage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return MinePageState();
  }
}

class MinePageState extends State<MinePage> with RouteAware {
  // final GlobalKey<BannerWidgetState> _bannerKey = GlobalKey();

  final MinePageController model = Get.put(MinePageController());

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context)! as PageRoute);
  }

  @override
  void dispose() {
    Get.delete<MinePageController>(force: true);
    super.dispose();
    routeObserver.unsubscribe(this);
  }

  @override
  void didPopNext() {
    super.didPopNext();
    if (GlobalConfig.bottomBarIndex == 2) {
      _refreshInfo();
    }
  }

  _refreshInfo() async {
    await UserManager.instance.refreshUserInfo();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
      value: SystemUiOverlayStyle.dark,
      child: GetBuilder<MinePageController>(builder: (logic) {
        return Stack(
          children: [
            Scaffold(
              floatingActionButton: FloatingActionButton(
                heroTag: "MinePage",
                onPressed: () {
                  // _showLanguageDialog(context);
                  _showLanguageDialog(context);
                },
                child: const Icon(Icons.language), // 示例图标
              ),
              body: SingleChildScrollView(
                controller: logic.controller,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SizedBox(
                      height: ScreenUtil().statusBarHeight,
                    ),
                    personModule(),
                    SizedBox(
                      height: 20.h,
                    ),
                    // personToolWidget(),
                    SizedBox(
                      height: 12.h,
                    ),
                    // BannerWidget(
                    //   key: _bannerKey,
                    //   margin:
                    //       EdgeInsets.only(bottom: 12.h, left: 20.w, right: 20.w),
                    //   autoPlay: true,
                    // ),
                    SizedBox(
                      height: 0.h,
                    ),
                    // personSettingsWidget(),
                    const SizedBox(
                      height: 26,
                    ),
                    Text(
                      T.current.no_more_data,
                      style: TextStyle(
                          fontSize: 12.sp, color: const Color(0xFF999999)),
                    ),
                    const SizedBox(
                      height: 90,
                    ),
                  ],
                ),
              ),
            ),
            IgnorePointer(
              child: Opacity(
                opacity: fixMath.max(fixMath.min(model.opacity, 1), 0),
                child: Wrap(
                  children: [
                    AppBar(
                      title: const Text(
                        'nickname',
                        style: TextStyle(
                            color: Color(0xFF333333),
                            fontSize: 16,
                            fontWeight: FontWeight.w600),
                      ),
                      centerTitle: true,
                      elevation: 0,
                      // ignore: prefer_const_literals_to_create_immutables
                      backgroundColor: Colors.white,
                    )
                  ],
                ),
              ),
            ),
          ],
        );
      }),
    );
  }

  Widget personModule() {
    var nikeName = model.user.nickname;
    return Container(
      width: double.infinity,
      padding: EdgeInsets.only(
        top: 32.h,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CupertinoButton(
            onPressed: () async {
              // await PersonalHomePage.show(
              //     context, UserManager.instance.currentUid,
              //     visitRecord: true);
              // model.updateUser();
            },
            minSize: 0,
            padding: EdgeInsets.zero,
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 20.w),
              child: Row(
                mainAxisSize: MainAxisSize.max,
                children: [
                  GestureDetector(
                    onTap: () async {
                      // await Get.to(() => const PortraitPage());
                      // model.updateUser();
                    },
                    child: Stack(
                      children: [
                        // AvatarImage(
                        //   url: model.user.hasAvatarAudit()
                        //       ? model.user.avatarAudit
                        //       : model.user.avatar,
                        //   width: 60.w,
                        //   height: 60.w,
                        //   shape: BoxShape.circle,
                        // ),
                        // model.user.hasAvatarAudit()
                        //     ? Container(
                        //         width: 60.w,
                        //         height: 60.w,
                        //         alignment: Alignment.center,
                        //         decoration: BoxDecoration(
                        //             color: Colors.black.withOpacity(0.5),
                        //             shape: BoxShape.circle),
                        //         child: Text(
                        //           T.current!.reviewing,
                        //           style: TextStyle(
                        //               color: Colors.white, fontSize: 12.sp),
                        //           textAlign: TextAlign.center,
                        //         ),
                        //       )
                        //     : const SizedBox.shrink()

                        const Text('我的'),
                      ],
                    ),
                  ),
                  SizedBox(
                    width: 12.w,
                  ),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // Text(
                        //   nikeName,
                        //   maxLines: 1,
                        //   overflow: TextOverflow.ellipsis,
                        //   style: JRTextStyles.styleFont18W600
                        //       .copyWith(color: JR.color.mainText),
                        // ),
                        SizedBox(
                          height: 10.h,
                        ),
                        // IDWidget(id: model.user.id.toString(), showCopy: true),
                      ],
                    ),
                  ),
                  SizedBox(
                    width: 12.w,
                  ),
                  image('ic_arrow.svg', width: 14.w, height: 14.w),
                ],
              ),
            ),
          ),
          SizedBox(
            height: 28.h,
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Text('xxx'), Text('xxx'),
                // _personRelationNumWidget("${model.user.friendNum}",
                //     T.current!.friend, model.user.newFriendCount),
                // _personRelationNumWidget("${model.user.followNum}",
                //     T.current!.follow, $fixnum.Int64(0)),
                // _personRelationNumWidget("${model.user.fanNum}",
                //     T.current!.fans, model.user.newFollowerCount),
                // _personRelationNumWidget("${model.user.viewNum}",
                //     T.current!.visitor, model.user.newVisitorCount),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // Widget personToolWidget() {
  //   return Container(
  //     width: double.infinity,
  //     margin: EdgeInsets.only(left: 20.w, right: 20.w),
  //     padding: EdgeInsets.only(top: 18.w, bottom: 20.w),
  //     decoration: BoxDecoration(
  //         color: Colors.white,
  //         borderRadius: BorderRadius.all(Radius.circular(8.w)),
  //         boxShadow: [
  //           BoxShadow(
  //               color: Colors.black.withOpacity(0.08),
  //               offset: Offset(0, 4.h),
  //               blurRadius: 16.r)
  //         ]),
  //     child: GridView.builder(
  //         padding: EdgeInsets.zero,
  //         shrinkWrap: true,
  //         itemCount: MinePageItem.values.length,
  //         gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
  //           crossAxisCount: 4,
  //           crossAxisSpacing: 0,
  //           mainAxisSpacing: 10.w,
  //           childAspectRatio: 82 / 62,
  //         ),
  //         itemBuilder: (context, index) {
  //           return _personItemWidget(MinePageItem.values[index]);
  //         }),
  //   );
  // }

  Widget bannerWidget(bool boos, String urlStr) {
    if (urlStr.isNotEmpty) {
      /// 走网络请求不用判断是否是车手
      return image(urlStr, fit: BoxFit.fitWidth);
    } else {
      if (boos) {
        return image("mine_contact_banner_1.png", fit: BoxFit.fitWidth);
      } else {
        return image("mine_contact_banner_2.png", fit: BoxFit.fitWidth);
      }
    }
  }

// 选择本地语言
  void _showLanguageDialog(BuildContext context) {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
      ),
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsetsDirectional.all(16.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: T.delegate.supportedLocales.map((locale) {
              return ListTile(
                title: Text(_getLanguageName(context, locale)),
                onTap: () async {
                  // 新增持久化存储
                  await CacheUtil.set(
                      CacheKeys.languageCode, locale.languageCode);
                  // meController.updateLanguageCode(locale.languageCode);
                  await Get.updateLocale(locale);
                  Get.forceAppUpdate(); // 添加强制更新
                  Navigator.of(context).pop();
                },
              );
            }).toList(),
          ),
        );
      },
    );
  }

  // 弹框选择展示，这个可以继续优化，不然每次增加语种这里也要增加相对应代码！
  String _getLanguageName(BuildContext context, Locale locale) {
    switch (locale.languageCode) {
      case 'en':
        return T.current.language_en;
      case 'zh':
        return T.current.language_zh;
      case 'ar':
        return T.current.language_ar;
      default:
        return T.current.language_unknown;
    }
  }

  // Widget personSettingsWidget() {
  //   return Container(
  //       width: double.infinity,
  //       padding: EdgeInsets.symmetric(horizontal: 18.w),
  //       decoration: BoxDecoration(
  //         borderRadius: BorderRadius.all(
  //           Radius.circular(8.r),
  //         ),
  //         color: Colors.white,
  //       ),
  //       alignment: Alignment.center,
  //       child: Column(
  //         children: [
  //           if (GlobalConfig.isDebug)
  //             _personSettingItemWidget(
  //                 "assets/images/mine_tag_certificate_setting.png",
  //                 T.current!.debug_page, onPressed: () {
  //               Navigator.of(context).push(CupertinoPageRoute(
  //                   builder: (context) => const DebugPage()));
  //             }),
  //           if (UserManager.instance.currentUser?.email.isNotEmpty != true &&
  //               UserManager.instance.currentUser?.job != Job.BOSS &&
  //               UserManager.instance.currentUser?.isGsGroupUser == true)
  //             _personSettingItemWidget(
  //                 "assets/images/mine_tag_certificate_setting.png",
  //                 T.current!.mine_bind_email, onPressed: () {
  //               ThirdLoginPlatformFactory.ins
  //                   .getPlatform(LoginPlatform.email.name)
  //                   ?.bindEmail();
  //             }),
  //           if (!GlobalConfig.hiddenAction)
  //             _personSettingItemWidget(
  //               "assets/images/mine_tag_certificate_setting.png",
  //               T.current!.certification_center,
  //               onPressed: () {
  //                 Navigator.of(context).push(CupertinoPageRoute(
  //                     builder: (context) => const AuthCenterPage()));
  //               },
  //             ),
  //           if (model.user.job != Job.BOSS && !GlobalConfig.hiddenAction)
  //             _personSettingItemWidget(
  //                 "assets/images/mine_tag_radio_setting.png",
  //                 T.current!.guest_workbench, onPressed: () async {
  //               if (model.user.gsGroupId.toInt() > 0) {
  //                 JrNavigator.navigateToWorkBench();
  //               } else {
  //                 JRDialog.showCommonDialog(
  //                     context: context,
  //                     data: TextWithOneBtnDialogData(
  //                         title: T.current!.join_guild_first,
  //                         desc: T.current!.join_guild_tips));
  //               }
  //             }),
  //           if (model.user.inviteCodeEntrance.isNotEmpty)
  //             _personSettingItemWidget("assets/images/mine_tag_invite.png",
  //                 T.current!.my_invite_code, onPressed: () {
  //               CommonWebView.show(context, model.user.inviteCodeEntrance,
  //                   title: T.current!.my_invite_code);
  //             }),
  //           _personSettingItemWidget("assets/images/mine_tag_edit_setting.png",
  //               T.current!.perfect_info, onPressed: () async {
  //             await Navigator.of(context).push(CupertinoPageRoute(
  //                 builder: (context) => const MineDataEditPage()));
  //             model.update();
  //           }, tip: T.current!.completed_few_progress(model.dataIntegrity)),
  //           _personSettingItemWidget(
  //               "assets/images/mine_tag_setting.png", T.current!.setting,
  //               onPressed: () {
  //             Navigator.of(context).push(CupertinoPageRoute(builder: (context) {
  //               return const SettingPage();
  //             }));
  //           }),
  //           _personSettingItemWidget(
  //               "assets/images/mine_tag_helpcenter_setting.png",
  //               T.current!.help, onPressed: () {
  //             Navigator.of(context).push(CupertinoPageRoute(builder: (context) {
  //               return PrivacyWebView(
  //                 title: "",
  //                 url: "${UrlConfig.pageDomain}/Help",
  //               );
  //             }));
  //           }),
  //           // _personSettingItemWidget(
  //           //   "assets/images/mine_tag_service_setting.png",
  //           //   T.current!.customer_service,
  //           //   onPressed: (){
  //           //     bool isBoss = UserManager.instance.currentUser?.job == Job.BOSS;
  //           //     if(isBoss){
  //           //       showDialog(
  //           //         barrierDismissible: true,
  //           //         context: rootNavigatorState.currentState!.context,
  //           //         builder: (context) {
  //           //           return const MineBusinessCard(resourceType:ResourceType.BOSS_BANNER_MANAGER,);
  //           //         },
  //           //       );
  //           //     } else {
  //           //       /// 打开微信客服
  //           //       Resource.instance.getTeenResourceData(ResourceType.REGISTER_GS_WECHAT_LINK).then((value) {
  //           //         if(!value.isSuccess){
  //           //           showToast("${value.errorMsg}");
  //           //           return;
  //           //         }
  //           //         String url = value.data!.datas[0].link;
  //           //         _launchUrl(url);
  //           //       });
  //           //     }
  //           //   },
  //           // ),
  //           _personSettingItemWidget(
  //               "assets/images/mine_tag_aboutus_setting.png",
  //               T.current!.about_us, onPressed: () {
  //             Navigator.of(context).push(CupertinoPageRoute(builder: (context) {
  //               return AboutPage();
  //             }));
  //           }),
  //         ],
  //       ));
  // }

  // Widget _personSettingItemWidget(String url, String text,
  //     {VoidCallback? onPressed, String? tip}) {
  //   return CupertinoButton(
  //     onPressed: onPressed,
  //     padding: EdgeInsets.symmetric(vertical: 16.w),
  //     minSize: 0,
  //     child: Row(
  //       children: [
  //         Image.asset(
  //           url,
  //           width: 24.w,
  //           height: 24.w,
  //         ),
  //         SizedBox(
  //           width: 9.w,
  //         ),
  //         Expanded(
  //           child: Text(
  //             text,
  //             style: JRTextStyles.styleFont14W600
  //                 .copyWith(color: JR.color.mainText, fontSize: 14.sp),
  //           ),
  //         ),
  //         tip != null
  //             ? Text(
  //                 tip,
  //                 style: JRTextStyles.styleFont12W400
  //                     .copyWith(color: JR.color.secondaryText, fontSize: 12.sp),
  //               )
  //             : const SizedBox.shrink(),
  //         image('ic_arrow.svg', width: 14.w, height: 14.w),
  //       ],
  //     ),
  //   );
  // }

  // Widget _personItemWidget(MinePageItem item) {
  //   String name = '';
  //   String icon = '';
  //   VoidCallback? onPressed;
  //   switch (item) {
  //     case MinePageItem.wallet:
  //       name = T.current!.wallet;
  //       icon = 'mine_tag_wallet.webp';
  //       onPressed = () {
  //         Get.to(() => const MyWalletPage(), routeName: '/MyWalletPage');
  //       };
  //       break;
  //     case MinePageItem.car:
  //       name = T.current!.drive_car;
  //       icon = 'mine_tag_car.webp';
  //       onPressed = () {
  //         Get.to(() => const MineCarsPage(), routeName: '/MineCarsPage');
  //       };
  //       break;
  //     case MinePageItem.dress:
  //       name = T.current!.dress;
  //       icon = 'mine_tag_dress.webp';
  //       onPressed = () {
  //         MineDressPage.show();
  //       };
  //       break;
  //     case MinePageItem.level:
  //       name = T.current!.level;
  //       icon = 'mine_level.webp';
  //       onPressed = () {
  //         Get.to(() => const MineLevelPage(), routeName: '/MineLevelPage');
  //       };
  //       break;
  //     case MinePageItem.knight:
  //       name = T.current!.knight;
  //       icon = 'mine_knight.webp';
  //       onPressed = () {
  //         Get.to(() => const MineKnightPage(), routeName: '/MineKnightPage');
  //       };
  //       break;
  //   }

  //   return CupertinoButton(
  //     onPressed: onPressed,
  //     minSize: 0,
  //     padding: EdgeInsets.zero,
  //     child: Column(
  //       mainAxisSize: MainAxisSize.min,
  //       children: [
  //         JR.img(
  //           icon,
  //           width: 42.w,
  //           height: 42.w,
  //         ),
  //         const Spacer(),
  //         Text(
  //           name,
  //           maxLines: 1,
  //           style: JRTextStyles.styleFont13W400
  //               .copyWith(color: JR.color.mainText, fontSize: 13.sp),
  //         ),
  //       ],
  //     ),
  //   );
  // }

  // Widget _personRelationNumWidget(
  //     String num, String title, $fixnum.Int64 newFollowerCount) {
  //   return CupertinoButton(
  //     onPressed: () {
  //       if (title == T.current!.visitor) {
  //         Navigator.of(context)
  //             .push(MaterialPageRoute(
  //                 builder: (context) => const ViewUserScreen()))
  //             .then((value) => model.updateUser());
  //         return;
  //       }
  //       if (title == T.current!.friend) {
  //         Navigator.of(context)
  //             .push(
  //               MaterialPageRoute(
  //                 builder: (context) => UserRelationScreen(
  //                   index: 0,
  //                   type: T.current!.friend,
  //                 ),
  //               ),
  //             )
  //             .then((value) => model.updateUser());
  //         return;
  //       }
  //       if (title == T.current!.follow) {
  //         Navigator.of(context)
  //             .push(MaterialPageRoute(
  //                 builder: (context) => UserRelationScreen(
  //                       index: 1,
  //                       type: T.current!.follow,
  //                     )))
  //             .then((value) => model.updateUser());
  //         return;
  //       }
  //       if (title == T.current!.fans) {
  //         // Navigator.of(context).push(CupertinoPageRoute(
  //         //     builder: (context) => const IMContact()));

  //         Navigator.of(context)
  //             .push(MaterialPageRoute(
  //                 builder: (context) => UserRelationScreen(
  //                       index: 2,
  //                       type: T.current!.fans,
  //                     )))
  //             .then((value) => model.updateUser());
  //         return;
  //       }
  //     },
  //     minSize: 0,
  //     padding: EdgeInsets.zero,
  //     child: Column(
  //       mainAxisSize: MainAxisSize.min,
  //       children: [
  //         TextWidgetBadge(
  //           text: num,
  //           num: newFollowerCount.toInt(),
  //         ),
  //         SizedBox(
  //           height: 8.h,
  //         ),
  //         Text(
  //           title,
  //           style: JRTextStyles.styleFont12W400
  //               .copyWith(color: JR.color.tipsText, fontSize: 12.sp),
  //         ),
  //       ],
  //     ),
  //   );
  // }

  // Future refresh() async {
  //   var futures = [
  //     if (_bannerKey.currentState != null) _bannerKey.currentState!.refresh(),
  //     model.updateUser()
  //   ];
  //   return Future.wait(futures);
  // }
}

class TextWidgetBadge extends StatelessWidget {
  final String text;
  final int num;
  const TextWidgetBadge({Key? key, required this.text, required this.num})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    var textStyle = JRTextStyles.styleFont18W600
        .copyWith(color: JR.color.mainText, fontSize: 18.sp)
        .numFontFamily;
    var textPainter = TextPainter(
        text: TextSpan(text: text, style: textStyle),
        textDirection: TextDirection.ltr);
    textPainter.layout();
    var textWidth = textPainter.width;
    return Stack(
      clipBehavior: Clip.none,
      alignment: Alignment.center,
      children: [
        Text(
          text,
          style: textStyle,
        ),
        // if (num > 0)
        //   PositionedDirectional(
        //       start: textWidth - 2,
        //       top: -4,
        //       child: RedPointWidget(
        //           count: num,
        //           height: 12.h,
        //           space: 4.w,
        //           textStyle: TextStyle(fontSize: 9.sp, color: Colors.white))),
      ],
    );
  }
}
